package com.ironman.h6b1gw.tlv;

import cn.hutool.core.util.HexUtil;
import lombok.Builder;
import lombok.Getter;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class TLVDecoder {

    /**
     * TLV解码器（假设T和L各占2字节，大端序）
     *
     * @param data 输入的字节数组
     * @return 解码后的TLV对象列表
     * @throws IllegalArgumentException 数据不完整或格式错误
     */
    public static List<TlvEntry> decode(byte[] data) {
        List<TlvEntry> entries = new ArrayList<>();
        ByteBuffer buffer = ByteBuffer.wrap(data);
        buffer.order(java.nio.ByteOrder.BIG_ENDIAN); // 大端序（高位在前）
        while (buffer.remaining() >= 4) { // 至少需要4字节（T+L）
            // 1. 解析Type（2字节）
            int type = buffer.getShort() & 0xFFFF; // 转为无符号整数

            // 2. 解析Length（2字节）
            int length = buffer.getShort() & 0xFFFF; // 转为无符号整数

            // 检查剩余数据是否足够
            if (buffer.remaining() < length) {
                throw new IllegalArgumentException("数据不完整: 期望长度 " + length + "，实际剩余 " + buffer.remaining());
            }

            // 3. 提取Value
            byte[] value = new byte[length];
            buffer.get(value);

            entries.add(new TlvEntry(String.format("%04X", type), length, HexUtil.encodeHexStr(value, false)));
        }
        return entries;
    }

    /**
     * TLV条目实体类
     */
    @Getter
    @Builder
    public static class TlvEntry {

        private final String type;

        private final int length;

        private final String value;

        @Override
        public String toString() {
            return String.format("T: %s, L: %d, V: %s", type, length, value);
        }
    }

    // 测试代码
    public static void main(String[] args) {
        String tlvStr = "02B20002000102B40002001502B60004B46B6D6602DA0002075B035C00020258035E0002000A036000020000036C00020000037000020000037200020000037400020000037600020000037800080000000000000000038000080000000000000000038A00080000000000000000039200080000000000000000039A0008000000000000000003A20002000003A40008000000000000000003AC0002000003AE000600000000000003B40002000003B60008000000000000000003BE0002000003C0000600000000000003C60002000003C80008000000000000000003D00002000003D2000600000000000003D80002000003DA0008000000000000000003E20002000003E4000600000000000003EA0002000003EC0008000000000000000003F40002000003F6000600000000000003FC00020000";
        byte[] bytes = HexUtil.decodeHex(tlvStr);
        List<TlvEntry> decode = decode(bytes);
        for (TlvEntry entry : decode) {
            System.out.println(entry);
        }
    }
}
